#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>
#include <cstring>
#include <strings.h>
#include <string>

int main()
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd == -1)
    {
        std::cerr << "建立网络套接字文件失败！" << std::endl;
        exit(0);
    }
    sockaddr_in local;
    bzero(&local, sizeof(local));
    if(inet_pton(AF_INET, "127.0.0.1", &local.sin_addr) != 1)
    {
        std::cerr << "网络字节序转换失败！" << std::endl;
        exit(0);   
    }
    local.sin_family = AF_INET;
    local.sin_port = htons(8888);
    while(true)
    {
        //发送消息
        std::string inbuffer;
        std::cout << "Please Enter# " << std::flush;
        std::getline(std::cin, inbuffer);
        ssize_t n = sendto(sockfd, inbuffer.c_str(), inbuffer.size(), 0, (sockaddr*)&local, sizeof(local));
        if(n == -1)
        {
            std::cerr << "当前发送消息失败！" << std::endl;
            exit(0);
        }
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr*)&temp, &len);
        if(m == -1)
        {
            std::cerr << "当前接收消息失败！" << std::endl;
            exit(0);
        }
        buffer[m] = 0;
        std::cout << "服务器发来消息：" << buffer << std::endl;
    }
    return 0;
}